package com.demo2.todo.service.impl;

import com.demo2.todo.exception.ResourceNotFoundException;
import com.demo2.todo.model.entity.Report;
import com.demo2.todo.model.entity.Todo;
import com.demo2.todo.model.entity.User;
import com.demo2.todo.model.enums.ReviewStatus;
import com.demo2.todo.repository.ReportRepository;
import com.demo2.todo.repository.TodoRepository;
import com.demo2.todo.repository.UserRepository;
import com.demo2.todo.service.AdminService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author evi
 */
@Service
@RequiredArgsConstructor
public class AdminServiceImpl implements AdminService {
    private final UserRepository userRepository;
    private final TodoRepository todoRepository;
    private final ReportRepository reportRepository;

    @Transactional
    @Override
    public void reviewTodo(Long id, ReviewStatus status, String comment) {
        Todo todo = todoRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("待办事项不存在"));
        todo.setReviewStatus(status);
        todoRepository.save(todo);
    }

    @Transactional
    @Override
    public void processReport(Long reportId, Report.ReportStatus status, Long adminId) {
        Report report = reportRepository.findById(reportId)
                .orElseThrow(() -> new ResourceNotFoundException("举报记录不存在"));
        report.setStatus(status);
        report.setProcessedAt(java.time.LocalDateTime.now());
        report.setProcessedBy(adminId);
        reportRepository.save(report);

        // 如果接受举报，处理对应的todo
        if (status == Report.ReportStatus.ACCEPTED) {
            Todo todo = todoRepository.findById(report.getTodoId()).orElse(null);
            if (todo != null) {
                todo.setReviewStatus(ReviewStatus.rejected);
                todoRepository.save(todo);
            }
        }
    }

    @Override
    @Transactional
    public void blacklistUser(Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));
//        user.setAccountNonLocked(false);
        user.setEnabled(false);
        userRepository.save(user);

        // 拉黑后处理用户的待办事项
        List<Todo> userTodos = todoRepository.findByUserIdOrderByCreatedAtDesc(userId);
        userTodos.forEach(todo -> {
            todo.setReviewStatus(ReviewStatus.rejected);
        });
        todoRepository.saveAll(userTodos);
    }
}